package com.code.bolg.controller;

import com.code.bolg.annotation.ReturnParam;
import com.code.bolg.config.SysConfig;
import com.code.bolg.enums.ResultEnum;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/file")
public class FileController {
    @Autowired
    private SysConfig sysConfig;
    DateFormat format = new SimpleDateFormat("yyyy/MM/dd/");

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    @ReturnParam(isPackage = false)
    public Map<String, Object> upload(@RequestParam("file") MultipartFile[] file) {
        Map<String, Object> map = new HashMap<>();
        List<String> list = new ArrayList<>();
        for (MultipartFile multipartFile : file) {
            String baseUpload = this.baseUpload(multipartFile);
            list.add(baseUpload);
        }
        map.put("errno", 0);
        map.put("data", list);
        return map;
    }


    private String baseUpload(MultipartFile file) {
         if (file.isEmpty()) {//判断文件为null
            return ResultEnum.FILEISNULL.getMessage();
        }

        String fileName = file.getOriginalFilename();//获取文件名
        String format = this.format.format(new Date());
        String path = sysConfig.getUploadPath() + format;   //自定义文件存放位置
        String suffix = fileName.substring(fileName.lastIndexOf("."));//获取文件后缀名
        String newName = UUID.randomUUID().toString() + suffix;
        File dest = new File(path);
        if (!dest.exists()) {
            dest.mkdirs();
        }
        if(!sysConfig.getImgtypes().contains(suffix)){
            return ResultEnum.ILLEGALFILE.getMessage();
        }
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(path + newName);
            out.write(file.getBytes());
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sysConfig.getImgPath() + format + newName;
    }

}
